package com.day14me.java;

public class ProductAndCustomerTwoTest {
    public static void main(String[] args) {
            StroeTwo st = new StroeTwo();
            ProductTwo pt1 = new ProductTwo();
            pt1.setStroe(st);
            ProductTwo pt2 = new ProductTwo();
            pt2.setStroe(st);
            ProductTwo pt3 = new ProductTwo();
            pt3.setStroe(st);

    }
}

class StroeTwo {
    private int items = 20;

    public void add() {//生产方法
        synchronized (this) {
            while (items >= 20) {
                System.out.println("商品数量已达上限，生产线程暂停，先让消费线程运行==");
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("生产线程正在运行，生产了一个商品，当前数量" + (++items) + "~~~");
            this.notifyAll();
        }
    }
public void get(){//消费方法
        synchronized(this){
            while(items<=0){
                System.out.println("仓库中已无库存商品，消费线程暂停，先让生产线程运行====");
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("消费线程正在运行，消费了一个商品，当前商品"+(++items)+"--");
            this.notifyAll();
        }
}
}
class ProductTwo extends Thread{
    private StroeTwo stroe;

    public StroeTwo getStroe() {
        return stroe;
    }

    public void setStroe(StroeTwo stroe) {
        this.stroe = stroe;
    }

    @Override
    public void run() {
        while(true){
            System.out.println(this.getName()+"线程正在运行~~~~~");
            stroe.add();
        }
    }
}
class CustmoerTwo extends Thread{
    private StroeTwo store;

    public StroeTwo getStore() {
        return store;
    }

    public void setStore(StroeTwo store) {
        this.store = store;
    }

    @Override
    public void run() {
        while(true){
            try {
                sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(this.getName()+"线程正在运行~~~~");
            store.get();
        }
    }
}

